package com.hczt.fire.server.backend.sys.service.impl;

import com.hczt.fire.entity.sys.*;
import com.hczt.fire.framework.jpa.repository.IBaseDao;
import com.hczt.fire.framework.jpa.repository.support.QueryCriteria;
import com.hczt.fire.server.backend.sys.service.SysPermissionService;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.ListJoin;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * @author marvin.ma
 * @create 2017-10-19 23:15
 * @desc 权限实现
 **/
@Service
public class SysPermissionServiceImpl implements SysPermissionService {

    @Resource
    IBaseDao baseDao;

    /**
     * 根据资源名称模糊匹配
     *
     * @param menuName
     * @return
     */
    @Override
    public List<SysPermission> findListByMenuName(String menuName) {
        QueryCriteria<SysPermission, SysPermission> criteria = baseDao.getCriteriaQuery(SysPermission.class, SysPermission.class);
        CriteriaBuilder builder = criteria.getBuilder();
        Root<SysPermission> root = criteria.getEntity();
        if(StrUtil.isNotEmpty(menuName)) {
            Predicate condition = builder.equal(root.get(SysPermission_.name), menuName);
            criteria.getQuery().where(condition);
        }
        return baseDao.findListByCriteriaQuery(criteria.getQuery());
    }

    /**
     * 获取角色里的菜单权限
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysPermission> findByUserId(Long userId) {
        QueryCriteria<SysPermission, SysUser> criteria = baseDao.getCriteriaQuery(SysPermission.class, SysUser.class);
        ListJoin<SysUser, SysRole> join = criteria.getEntity().join(SysUser_.sysRoles);
        ListJoin<SysRole, SysPermission> join1 = join.join(SysRole_.sysPermissions);

        Predicate condition = criteria.getBuilder().equal(criteria.getEntity().get(SysUser_.id), userId);
        criteria.getQuery().where(condition);
        criteria.getQuery().select(join1).distinct(true);
        return baseDao.findListByCriteriaQuery(criteria.getQuery());
    }


}
